package org.jgs1904.apachepoidemo.utils;

import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author: 默苍璃
 * @date: 2023-10-12 15:19
 */
public class ImageToCellExample {

    public static void main(String[] args) {
        // 创建工作簿和工作表
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        try {
            // 下载图片文件并保存到本地
            URL imageUrl = new URL("https://tse2-mm.cn.bing.net/th/id/OIP-C.yOlhod8-7z_gwTQW8yVedQHaHa?w=226&h=180&c=7&r=0&o=5&pid=1.7"); // 图片的URL
            BufferedImage image = ImageIO.read(imageUrl);
            File outputFile = new File("image.jpg"); // 指定要保存的本地文件名
            ImageIO.write(image, "jpg", outputFile);

            // 读取图片文件并插入到单元格中
            FileInputStream fis = new FileInputStream(outputFile);
            byte[] imageBytes = IOUtils.toByteArray(fis);
            int pictureIndex = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_JPEG); // 将图片添加到工作簿
            fis.close();

            CreationHelper creationHelper = workbook.getCreationHelper();
            Drawing drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = creationHelper.createClientAnchor();

            anchor.setCol1(1); // param1是列号
            anchor.setRow1(1); // param2是行号

// 插入图片
            Picture pict = drawing.createPicture(anchor, pictureIndex);
// 调整图片占单元格百分比的大小，1.0就是100%

            pict.resize(1.0);


            // 保存工作簿到文件
            FileOutputStream fos = new FileOutputStream("D:\\temp\\output.xlsx");
            workbook.write(fos);
            fos.close();

            System.out.println("图片已成功插入到单元格中！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
